<template>
	<view class="">
		<uni-section title="回合控制" type="line" class="gameStageControl" v-show="stageControl">
			<uni-notice-bar text="点击[手动切换],结束夜晚或创建新回合" />
			<view class="currentstage-vote-control">
				<view class="currentstage">
					当前回合：{{gameStageCodeTrans}}
				</view>
				<view class="currentstage-toggle">
					<view class="control-btn">
						<button :loading="voteLoading" :disabled="voteDisable" class="mini-btn" type="primary" size="mini"
							@click="startVote">{{voteBtnText}}</button>
					</view>
					<view class="control-btn">
						<button class="mini-btn" :disabled="!voteLoading" type="error" size="mini" @click="endVote">结束投票</button>
					</view>
				</view>
			</view>
			<view class="currentstage-toggle">
				<view class="toggle-text">
					切换至
					<uni-combox class="toggle-combox" :candidates="gameStageList" placeholder="游戏回合选择"
						v-model="selectedGameStage">
					</uni-combox>
					<view class="control-btn">
						<button class="toggle-combox" type="primary" size="mini" @click="gameStageChange">手动切换</button>
					</view>
				</view>
			</view>
			<view class="currentstage-endgame">
				<button class="min-btn" type="warn" size="mini" @click="endGame">结束游戏</button>
			</view>
		</uni-section>
		<gameInfo v-show="!stageControl"  :num="gamePlayerNum" :status="gameProcessStatus" :date="$utils.formatDate(currentGameDTO.date)"/>
		<seat v-show="!stageControl" seatTitle="主持人分配座位" seatTip="主持人可点击座位手动分配,或踢出玩家" :seatList="gameSeatList" />
		<uni-section title="游戏管理" type="line" class="gameManage">
			<view class="dm-control">
				<view class="control-btn">
					<button class="managebtn" type="primary" size="mini" @click="toGameStageAction">管理游戏信息</button>
				</view>
			</view>
			<view class="dm-control">
				<view class="control-btn">
					<button v-if="toggleButton" class="viewbtn" type="primary" size="mini"
						@click="subGameStageControl">回合控制</button>
					<button v-else class="viewbtn" type="primary" size="mini"
						@click="subGameStageControl">游戏主界面</button>
				</view>
				<view class="control-btn">
					<button class="mini-btn" type="primary" size="mini" @click="toVoteHistory">查看投票记录</button>
				</view>
			</view>
		</uni-section>
		<view>
			<!-- 开始投票确认框 -->
			<uni-popup ref="startVoteDialog" type="dialog">
				<uni-popup-dialog type="warn" content="即将开始投票,请确认发言结束以及完成玩家行为录入" title="投票确认" @confirm="subStartVote">
				</uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 结束投票确认框 -->
			<uni-popup ref="endVoteDialog" type="dialog">
				<uni-popup-dialog type="warn" content="游戏回合即将切换,请确认是否完成玩家行为录入" title="玩家行为录入确认" @confirm="subEndVote">
				</uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 玩家行为录入确认框 -->
			<uni-popup ref="playerActionConfirmDialog" type="dialog">
				<uni-popup-dialog type="warn" content="游戏回合即将切换,请确认是否完成玩家行为录入/投票" title="玩家行为录入确认"
					@confirm="subGameStageChange">
				</uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 结束游戏确认框 -->
			<uni-popup ref="endGameConfirmDialog" type="dialog">
				<uni-popup-dialog type="warn" title="退出游戏" content="请确认是否结束本场游戏？" @confirm="subEndGame()">
				</uni-popup-dialog>
			</uni-popup>
		</view>
		<!-- 网络请求结果确认框 -->
		<uni-popup ref="resultMessage" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000">
			</uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import statusBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-status-bar";
	import gameInfo from '@/components/gameinfo.vue'
	import seat from '@/components/seat.vue'
	import {querygamedetailbydm} from "@/common/api"
	import {formatDate,GAME_ID,GAME_STATUS,GAME_STAGE} from "@/common/utils"
	import {createcurrentround,endcurrentnight,startvote,endvote,endgame} from "@/common/api"
	import {mapState,mapMutations,mapGetters,mapActions} from "@/store/helper/dm"
	export default {
		name: 'manage-game',
		components: {statusBar,gameInfo,seat},
		data() {
			return {
				stageControl: false,
				toggleButton: true,
				gameStageList:["首夜", "警长竞选", "第一日", "第一夜", "第二日", "第二夜", "第三日", "第三夜", "第四日", "第四夜", "第五日", "第五夜", "第六日",
					"第六夜", "第七日","第七夜", "第八日", "第八夜", "第九日", "第九夜", "第十夜", "警长竞选2"],
				currentGameStage: "",
				selectedGameStage: "",
				msgType: '',
				messageText: '',
			};
		},
		computed: {
			voteBtnText(){
				return this.gameStageVoteStatus=== 'voting'?'投票中':'开始投票'
			},
			voteLoading(){
				return this.gameStageVoteStatus==='voting'?true:false
			},
			voteDisable(){
				return this.gameStageVoteStatus==='not_need_vote'?true:false
			},
			...mapState([
				"currentGameID",
				"currentGameDTO",
				"gameStatus",
				"gameStageCode",
				"gameStageVoteStatus",
			]),
			...mapGetters([
				"gameStageCodeTrans",
				"gameSeatList",
				"gameProcessStatus",
				"gamePlayerNum",
			])
		},
		onLoad(option) {
			this.setGameStageCode(option.queryGameCode)
			uni.getStorageSync('GAME_STAGE')
			this.selectedGameStage = this.gameStageCodeTrans
			this.updatePlayerStatus()
		},
		onShow(){
			// #ifdef MP-WEIXIN
			//每隔5秒查询更新一次游戏信息
			let that = this
			this.timer = setInterval(function(){
				that.updatePlayerStatus();
				console.log(1);
				clearInterval(this.timer)
				},5000)
			if (this.gameStatus!= "init" ) {clearInterval(this.timer)}
			// #endif
		},
		onUnload() {
			//退出页面时判断当前游戏状态，如已结束则清空本地存储重置游戏状态
			if(this.gameStatus ==="human_win" || this.gameStatus ==="third_part_win" || this.gameStatus ==="wolf_win"){
				this.clearCurrentGame()
			}
		},		
		methods: {
			async updatePlayerStatus(){
				//更新玩家座位信息
				const {data,code,message} = await querygamedetailbydm({"code":this.currentGameID})
				if (data.code === "200") {
					this.setCurrentGameDTO(data.data.game)
					this.setGameStatus(data.data.game.processStatus)
					uni.setStorageSync('GAME_STATUS',this.gameStatus)
					this.setCurrentGameID(data.data.game.code)
					uni.setStorageSync('GAME_ID',this.currentGameID)
					this.setGameStageCode(data.data.gameProcessingInfo.curStageCode)
					uni.setStorageSync('GAME_STAGE',this.gameStageCode)
					//更新投票状态
					this.setGameStageVoteStatus(data.data.gameProcessingInfo.gameStageVoteStatus)
					//获取保存所有回合的行为信息(角色行为、投票限制/记录/结果)
					this.setGameStageInfoMap(data.data.gameProcessingInfo.stageInfoMap)
					//保存当前警长座位号
					this.setPoliceNum(data.data.gameProcessingInfo.police)
					this.messageToggle('success','刷新玩家准备信息成功')
				} else {
					this.messageToggle('error',`刷新玩家准备信息失败:` + data.message)
				}
			},
			messageToggle(type, text) {
				this.msgType = type
				this.messageText = text
				this.$refs.resultMessage.open()
			},
			subGameStageControl() {
				this.stageControl = !this.stageControl
				this.toggleButton = !this.toggleButton
			},
			startVote() {
				this.$refs.startVoteDialog.open()
			},
			async subStartVote() {
				const {code,data,message} = await startvote({"code": this.currentGameID})
				if (data.code === "200") {
					this.messageToggle('success', '投票开始，请指引玩家投票')
					//更新投票状态
					this.setGameStageVoteStatus(data.gameProcessingInfo.gameStageVoteStatus)
				} else {
					this.messageToggle('warn', data.message)
				}
			},
			endVote() {
				this.$refs.endVoteDialog.open()
			},
			async subEndVote() {
				const {code,data,message} = await endvote({"code": this.currentGameID})
				if (data.code === "200") {
					this.messageToggle('success', '投票成功结束')
					//更新投票状态
					this.updatePlayerStatus()
					this.setGameStageVoteStatus(data.data.gameProcessingInfo.gameStageVoteStatus)
					//保存所有回合的行为信息(角色行为、投票限制/记录/结果)
					this.setGameStageInfoMap(data.data.gameProcessingInfo.stageInfoMap)
				} else {
					this.messageToggle('warn', data.message)
				}
			},
			gameStageChange() {
				this.$refs.playerActionConfirmDialog.open()
			},
			//发起请求切换游戏回合
			async subGameStageChange() {
				//待优化为promise处理多个异步请求
				if (this.gameStageCode.includes('night')) {
					const {code,data,message} = await endcurrentnight({
						"code": this.currentGameID
					})
					if (data.code === "200") {
						this.messageToggle('success', '当前夜晚成功结束')
					} else {
						this.messageToggle('error', data.message)
					}
				}
				const {code,data,message} = await createcurrentround({
					"code": this.currentGameID
				})
				if (data.code === "200") {
					this.updatePlayerStatus()
					// this.setGameStageCode(data.data.gameProcessingInfo.curStageCode)
					// //回合历史设置本地缓存
					// uni.setStorageSync('GAME_STAGE',data.data.gameProcessingInfo.curStageCode)
					//当前选中项为当前回合
					this.currentGameStage = this.gameStageCodeTrans
					this.messageToggle('success', '当前回合已创建，进入下个白天/夜晚')
					//更新投票状态
					this.updateGameStageVoteStatus(data.data.gameProcessingInfo.gameStageVoteStatus)
				} else {
					this.messageToggle('error', data.message)
				}
			},
			endGame() {
				this.$refs.endGameConfirmDialog.open()
			},
			async subEndGame() {
				const {code,message} = await endgame({"code": this.currentGameID})
				if (data.code === "200") {
					this.setGameStageCode(data.gameProcessingInfo.curStageCode)
					this.messageToggle('success', '游戏已结束，撒花')
					//需要重置游戏状态
				} else {
					this.messageToggle('error', data.message)
				}
			},
			//管理游戏信息跳转
			toGameStageAction() {
				uni.navigateTo({
					url: `/pages/view/dm/manage-gameinfo?managestage=${this.gameStageCodeTrans}`
				})
			},
			//查看投票记录跳转
			toVoteHistory(){
				uni.navigateTo({
					url: `/pages/view/common/voterecode-history`
				})
			},
			...mapMutations([
				"setGameStageCode",
				"setGameStatus",
				"setCurrentGameID",
				"setCurrentGameDTO",
				"setGameStageVoteStatus",
				"setGameStageInfoMap",
				"setPoliceNum"
			]),
			...mapActions([
				"clearCurrentGame"
			])
		},
	};
</script>

<style scoped lang="scss">
	.gameStageControl,.gameManage {
		height: 270px;
	}

	.title {
		background-color: $uni-color-primary;
	}

	.managebtn {
		background-color: $uni-color-success;
		font-weight: 700;
	}

	.viewbtn {
		background-color: #f0f130;
		border: 1px solid #201C2A;
		color: #201C2A;
		font-weight: 700;
	}

	.dm-control,
	.currentstage-vote-control,
	.currentstage-toggle,
	.currentstage-endgame,
		{
		display: flex;
		justify-content: center;
		align-items: center;
		flex: 1;
	}

	.toggle-text {
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex: 1;
		margin-right: 10px;
	} 
	
	/*  #ifdef H5  */
	.toggle-combox {
		margin-right: 20px;
	}
	/*  #endif  */

	.currentstage,
	.toggle-text {
		margin-left: 10px;
		font-size: 14px;
	}

	.control-btn,
	.currentstage-endgame {
		margin: 10px;
	}
</style>
